/***************************************** 
 * Desc: UGUI根节点Inspector
 * @Author: GSan
 * @Email: 2087653648@qq.com
 * CreateDate: 2020-07-11 11:58:48
*****************************************/

using Common.UGUI.Base;
using Common.UGUI.View;
using System.Collections.Generic;
using UnityEditor;
using UnityEngine;

namespace Common.UserEditor.UGUIViewSpace {

	[CustomEditor(typeof(UGUIRoot))]
	[CanEditMultipleObjects]
	public class UGUIRootInspector : Editor {

		public override void OnInspectorGUI() {

			UnityEngine.Object[] objects = targets;
			int len = objects.Length;
			UGUIRoot[] uguiRoots = new UGUIRoot[len];
			for (int i = 0; i < len; ++i) {
				uguiRoots[i] = (UGUIRoot)objects[i];
			}

			UGUIViewInspector.ShowUGUIView(uguiRoots, base.OnInspectorGUI, new UGUIViewOnValueCallback());

			RefreshUGUIWholeTree(uguiRoots);
		}

        #region 自定义子面板

		private static void RefreshUGUIWholeTree(UGUIRoot[] roots) {

			//GUILayout.Space(UnityEditorCommonConfig.GUILayoutGapSpace);

            if (GUILayout.Button("刷新所有UGUI状态", UGUIViewInspector.UGUIViewSmallButton, GUILayout.ExpandWidth(false))) {

				foreach (var oneRoot in roots) {
					RefreshUGUI(oneRoot.Transform);
				}
			}
        }

		#endregion

		#region 刷新所有UGUI状态

		private static Queue<Transform> _travelTransformQueue = null;

		private static void RefreshUGUI(Transform parent) {

			if (_travelTransformQueue == null) _travelTransformQueue = new Queue<Transform>();

			UGUIView uguiView = parent.GetComponent<UGUIView>();
			uguiView.AutoFindParent(true);

			int childCount = parent.childCount;

			for (int i = 0; i < childCount; ++i) {
				_travelTransformQueue.Enqueue(parent.GetChild(i));
			}

			// 层序遍历
			while(_travelTransformQueue.Count > 0) {

				Transform child = _travelTransformQueue.Dequeue();

				uguiView = child.GetComponent<UGUIView>();
				if (uguiView != null) {
					uguiView.AutoFindParent(true);
				}

				childCount = child.childCount;

				for (int i = 0; i < childCount; ++i) {
					_travelTransformQueue.Enqueue(child.GetChild(i));
				}
			}

			_travelTransformQueue = null;
		}

        #endregion
    }
}
